package com.mtjx.Manager;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.ObjectUtil;

import com.mtjx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;

/**
 * 授权管理器
 *
 */
@Component
public class JwtTokenAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext requestAuthorizationContext) {

        //获取token
        HttpServletRequest request = requestAuthorizationContext.getRequest();
        String token = request.getHeader("Authorization");
        //判断token是否为空
        if(ObjectUtil.isEmpty(token)){
            return new AuthorizationDecision(false);
        }
        //解析数据
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT( "陌",token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(ObjectUtil.isEmpty(claims)){
            return new AuthorizationDecision(false);
        }

        //从缓存中获取url列表
        String accessUrlsCacheKey = (String) claims.get("username");
        List<String> object = (List<String>) redisTemplate.opsForValue().get(accessUrlsCacheKey);
        List<String> accessUrls = null;


        //当前请求路径： GET/nursing_project/**
        //String targetUrl = request.getMethod() + request.getRequestURI();
        String targetUrl = request.getRequestURI();

        //验证用户是否拥有该资源
        for (String url : object) {
            if(antPathMatcher.match(url, targetUrl)){
                return new AuthorizationDecision(true);
            }
        }
        //构建为false，会自动跳转为403错误
        return new AuthorizationDecision(false);
    }
}